package com.ohuang.jiaxiaotong.Activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.ohuang.jiaxiaotong.MyHttpURL;
import com.ohuang.jiaxiaotong.R;
import com.ohuang.jiaxiaotong.Util.EventMsgCode;
import com.ohuang.jiaxiaotong.Util.Ohuang;
import com.ohuang.jiaxiaotong.Util.Sys;
import com.ohuang.jiaxiaotong.base.BaseAc;
import com.ohuang.jiaxiaotong.entity.EventMsg;
import com.ohuang.jiaxiaotong.entity.User;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class UploadFileActivity extends BaseAc {
    private static String VIDEOPATH = "";//存放地址

    private String Suffix = "";//后缀名
    private ImageView imageView;
    private Button button_upload;
    private EditText editText_content;
    private String className;
    private String dataUrl = "", content = "";
    private User user;
    private static final int RE_SUCCESS = 0, RE_FAIL = 1, RE_ERROR = 2, RE_OTHER = 3;
    private Dialog dialogLoading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_file);
        EventBus.getDefault().register(this);
        Intent intent = getIntent();
        className = intent.getStringExtra("className");
        setTitle("上传资料");
        Ohuang.changeStatusBarTextImgColor(this, true);
        Objects.requireNonNull(getSupportActionBar()).setHomeAsUpIndicator(R.mipmap.icon_goback);//设置ActionBar返回按钮
        Sys.ReadRequestPower(this, this);
        initView();
    }

    private void initView() {
        editText_content = findViewById(R.id.edit_content_uploadFile);
        imageView = findViewById(R.id.img_addImg_uploadFile);
        button_upload = findViewById(R.id.btn_upload_UploadFile);
        imageView.setOnClickListener(v -> {
            Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, 66);
        });

        button_upload.setOnClickListener(v -> {
            content = editText_content.getText().toString();
            if (user != null) {
                if (Sys.isClick()) {
                    if ((!VIDEOPATH.isEmpty())) {//有文件先上传文件
                        dialogLoading = Ohuang.dialogLoadingshow(this, "正在上传");
                        String url =MyHttpURL.mainUrl+ "user/upload";
                        String filePath = VIDEOPATH;
                        String filename = filePath.substring(filePath.lastIndexOf("."));
                        if (".mp4".equals(filename) || ".avi".equals(filename)) {
                            Suffix = "mp4";
                        } else {
                            Suffix = "png";
                        }
                        try {
                            upload(url, filePath, filename);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else if ((!content.isEmpty())) {//没有文件 有文字直接上传文字
                        dialogLoading = Ohuang.dialogLoadingshow(this, "正在上传");
                        httpUpLoadFile();
                    } else {
                        Toast.makeText(this, "上传的内容不能为空", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    //上传文件
    private void upload(String url, String filePath, String fileName) throws Exception {
        OkHttpClient client = new OkHttpClient();
        final RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", fileName,
                        RequestBody.create(MediaType.parse("multipart/form-data"), new File(filePath)))
                .build();

        Request request = new Request.Builder()
//                .header("Authorization", "Client-ID " + UUID.randomUUID())
                .url(url)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                myHandler.sendEmptyMessage(RE_ERROR);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                dataUrl = response.body().string();
                httpUpLoadFile();
            }
        });
    }

    //上传信息
    private void httpUpLoadFile() {
        OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("className", className)
                .add("url", dataUrl)
                .add("dataContent", content)
                .add("username", user.getUsername())
                .add("suffixName", Suffix)
                .build();

        final Request request = new Request.Builder()
                .url(MyHttpURL.mainUrl + "teacher/fillData")
                .post(formBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {

                myHandler.sendEmptyMessage(RE_ERROR);

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                ResponseBody body = response.body();
                if (body != null) {
                    String code = body.string();
                    if ("success".equals(code)) {
                        myHandler.sendEmptyMessage(RE_SUCCESS);
                    } else if ("error".equals(code)) {
                        myHandler.sendEmptyMessage(RE_FAIL);
                    } else {
                        myHandler.sendEmptyMessage(RE_OTHER);
                    }
                    body.close();
                }
            }
        });
    }


    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case RE_SUCCESS:
                    dialogLoading.dismiss();
                    EventBus.getDefault().post(new EventMsg(EventMsgCode.CODE_5, "通知DataFragment"));
                    Ohuang.dialogshow(UploadFileActivity.this, "上传成功", "上传成功", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
                    break;
                default:
                    dialogLoading.dismiss();
                    Ohuang.dialogshow(UploadFileActivity.this, "上传失败", "网络错误");
                    break;

            }
        }
    };

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 66 && resultCode == RESULT_OK && null != data) {
            Uri selectedVideo = data.getData();
            String[] filePathColumn = {MediaStore.Video.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedVideo,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            VIDEOPATH = cursor.getString(columnIndex);
            cursor.close();
            Glide.with(this).load(new File(VIDEOPATH)).into(imageView);

        }
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        if (item.getItemId() == android.R.id.home) {//左上角返回按钮
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void GetUserEventBus(User user) {
        this.user = user;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
